package com.woniuxy.kaer.shop.service.impl;

import com.woniuxy.kaer.commons.util.Data;
import com.woniuxy.kaer.param.EvaluateOrderParam;
import com.woniuxy.kaer.param.EvaluateReplyParam;
import com.woniuxy.kaer.shop.config.WebSocketServer;
import com.woniuxy.kaer.shop.mapper.ProductOrderMapper;
import com.woniuxy.kaer.shop.model.ProductEvaluate;
import com.woniuxy.kaer.shop.mapper.ProductEvaluateMapper;
import com.woniuxy.kaer.shop.model.ProductOrder;
import com.woniuxy.kaer.shop.service.ProductEvaluateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郭建东
 * @since 2025年02月17日
 */
@Service
public class ProductEvaluateServiceImpl extends ServiceImpl<ProductEvaluateMapper, ProductEvaluate> implements ProductEvaluateService {

    @Resource
    private ProductOrderMapper productOrderMapper;

    @Resource
    private ProductEvaluateMapper productEvaluateMapper;

    @Override
    public void evaluate(EvaluateOrderParam param, Integer userId) throws Exception {
        ProductOrder productOrder = productOrderMapper.selectById(param.getProductOrderId());
        //判断订单是否存在
        if(productOrder==null||!productOrder.getUserId().equals(userId)){
            throw new Exception("订单不存在");
        }
        //判断订单状态
        if(!productOrder.getOrderState().equals(Data.ORDER_STATE_EVALUATE)){
            throw new Exception("订单状态异常");
        }
        //修改订单评价分数
        productOrder.setEvalute(param.getEvaluate());
        productOrder.setOrderState(Data.ORDER_STATE_FINISH);
        productOrderMapper.updateById(productOrder);
        //新增订单评价
        ProductEvaluate productEvaluate = new ProductEvaluate();
        productEvaluate.setProductOrderId(param.getProductOrderId());//订单编号
        productEvaluate.setUserId(userId);//用户编号
        productEvaluate.setProductOrderEvaluateScore(param.getEvaluate());//评价分数
        productEvaluate.setProductOrderEvaluateContent(param.getContent());//评价内容
        productEvaluateMapper.insert(productEvaluate);
        try {
            String message = "订单 " + param.getProductOrderId() + " 已评价，请及时回复。";
            WebSocketServer.sendInfo(message, "1");
        } catch (IOException e) {
            log.error("发送 WebSocket 消息失败: ", e);
        }
    }

    @Override
    public void evaluateReply(EvaluateReplyParam param, Integer managerId)throws Exception {
        ProductEvaluate productEvaluate = productEvaluateMapper.selectById(param.getProductOrderId());
        if(productEvaluate==null){
            throw new Exception("该商品订单评价不存在");
        }
        if(productEvaluate.getComment()!=null){
            throw new Exception("该商品订单评价已回复");
        }
        productEvaluate.setComment(param.getReply());
        productEvaluate.setManageId(managerId);
        productEvaluateMapper.updateById(productEvaluate);
    }
}
